<template>
	<view class="pay-box">
		<view class="pay-title">支付方式</view>
		<view class="item-box">
			<view class="item" v-for="(item, index) in data.payList" :key="index" @click="switchTab(index+1)">
				<image :src="$imgUrl + '/pay/wx-icon.png'" v-if="index == 0" class="icon-1" mode=""></image>
				<image :src="$imgUrl + '/pay/pay-icon.png'" v-if="index == 1" class="icon-1" mode=""></image>
				<view class="itm-title">{{item.label}}</view>
				<view>
					<image :src="$imgUrl + '/pay/checked-icon.png'" class="icon-2" v-if="checked == (index + 1)" mode=""></image>
					<image :src="$imgUrl + '/pay/unchecked-icon.png'" class="icon-2" v-else mode=""></image>
				</view>
			</view>
		</view>
		<view class="pay-btn">
			<!-- #ifdef MP-WEIXIN -->
			<!-- <button type="default" class="btn" v-if="!hasOpenId" open-type="getPhoneNumber" :disabled="isClick1" :class="{'isClick-style':isClick1}" @getphonenumber="wxChatLogin">去支付</button> -->
			<!-- <button type="default" class="btn" v-if="!hasOpenId" :disabled="isClick1" :class="{'isClick-style':isClick1}" @click="wxChatLogin">去支付</button> -->
			<view class="btn" @click="goPayFrist" :class="{'isClick-style':isClick2}">去支付</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
				<view class="btn" :class="{'isClick-style':isClick2}" @click="goPayFrist">去支付</view>
			<!-- #endif -->
		</view>
	</view>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue'
	import { onLoad,onShow } from "@dcloudio/uni-app"
	import { payOrder } from '@/common/API/pay'
	import { getOpenId, getPhone } from '@/common/API/wxchat'
	import store from '@/store'
	import config from '@/utils/config'
	import {debounce} from '@/utils/debounce'

	const checked = ref(null)
	const isClick1 = ref(false)
	const isClick2 = ref(false)
	const params = reactive({
		"appId": config.appId,
		"channelCode": null,
		"sourceBizId": null,
		"sourceBizType": null,
		"couponId": null
	})
	const hasOpenId = ref(false)
	const data = reactive({
		payList: []
	})
	// #ifdef MP-WEIXIN
		data.payList = reactive([
			{
				label: '微信支付',
				value:'tonglian_wx_miniapp',
			}
		])
	// #endif
	// #ifndef MP-WEIXIN
		data.payList = reactive([
			{
				label: '微信支付',
				value:'tonglian_wx_miniapp',
			},
			{
				label: '支付宝支付',
				value:'tonglian_alipay_miniapp',
			}
		])
	// #endif

	const switchTab = (val:number) => {
		checked.value = val
		params.channelCode = data.payList[val -1].value
		isClick1.value = false
		isClick2.value = false
	}
	//去支付
	const goPayFrist = () => {
		if(isClick2.value){
			return
		}else{
			isClick2.value = true
		}
		goPay()
	}
	//去支付
	const goPay = debounce(async () => {
		if(!checked.value){
			return
		}
		if(checked.value == 1){
			//app调起微信小程序
			// #ifdef APP-PLUS
			plus.share.getServices(async (res)=>{
				var sweixin = null;
				for (var i = 0; i < res.length; i++) {
					var t = res[i];
					if (t.id == 'weixin') {
						sweixin = t;
					}
				}

				let couponId = params.couponId?params.couponId.toString(): ""
				params.couponId = params.couponId?params.couponId.map((item)=>{
					return item
				}):[]
				let wxData = {
					"appId": params.appId,
					"channelCode": params.channelCode,
					"sourceBizId": params.sourceBizId,
					"sourceBizType": params.sourceBizType,
					"couponIds": params.couponId ? params.couponId : []
				}
				let result = await payOrder(wxData)
				let extraData = JSON.parse(result.otherContent)
				if (sweixin) {
					backPage()
					sweixin.launchMiniProgram({
						id: 'gh_e64a1a89a0ad',
						type: config.type,
						path: `/pages/orderDetail/orderDetail?appid=${extraData.appid}&body=${extraData.body}&cusid=${extraData.cusid}&limit_pay=${extraData.limit_pay}&notify_url=${extraData.notify_url}&paytype=${extraData.paytype}&randomstr=${extraData.randomstr}&remark=${extraData.remark}&reqsn=${extraData.reqsn}&sign=${extraData.sign}&signtype=${extraData.signtype}&trxamt=${extraData.trxamt}&version=${extraData.version}&validtime=${extraData.validtime}`
					});
				}
			}, function(e){
			    console.log(e);
			});
			// #endif
			//微信小程序支付
			// #ifdef MP-WEIXIN
				params.couponId = params.couponId?params.couponId.map((item)=>{
					return item
				}):[]
				let wxData = {
					"appId": params.appId,
					"channelCode": params.channelCode,
					"sourceBizId": params.sourceBizId,
					"sourceBizType": params.sourceBizType,
					"couponIds": params.couponId ? params.couponId : []
				}
				let result = await payOrder(wxData)
				let extraData = JSON.parse(result.otherContent)
				wx.openEmbeddedMiniProgram({
					appId: 'wxef277996acc166c3',
					extraData: extraData,
					success(res){
						console.log('res:----',res)
					},
					fail(err){
						console.log('err:----',err)
					},
				})
			// #endif
		}else if(checked.value == 2){
			// app调起支付宝支付
			params.couponId = params.couponId?params.couponId.map((item)=>{
				return item
			}):[];
			let aliData = {
				"appId": params.appId,
				"channelCode": params.channelCode,
				"sourceBizId": params.sourceBizId,
				"sourceBizType": params.sourceBizType,
				"couponIds": params.couponId ? params.couponId : []
			}
			let res = await payOrder(aliData)
			if(res){
				let payInfo = JSON.parse(res.otherContent)
				// let schemeurl = plus.runtime.arguments;
				console.log(payInfo.url)
				let platform = uni.getSystemInfoSync().platform;//获取平台判断
				if (platform == 'android') {
					plus.runtime.openURL(payInfo.url)
				} else if (platform == 'ios') {
					plus.runtime.launchApplication({
						action: payInfo.url
					},function(){})
				}
				backPage()
				isClick1.value = false
				isClick2.value = false
			}
		}
	},500)
	//调起支付后交互
	const backPage = () => {
		setTimeout(()=>{
			uni.navigateBack({
				delta: 2
			})
		},3000)
	}

	const wxChatLogin = debounce(async () => { //微信授权登录
		if(isClick1.value){
			return
		}else{
			isClick1.value = true
		}
		let openId = uni.getStorageSync("openId");
		if (!openId) {
			//获取手机号
			// if(e.detail.code){
				// let p = {
				// 	appId: config.NewWxChatAppId,
				// 	code: e.detail.code
				// }
				// let phone = await getPhone(p)
				// 获取openId
				uni.login({
					provider: 'weixin',
					success: (res) => {
						let data = {
							appId: config.NewWxChatAppId,
							code: res.code
						}
						console.log(data)
						getOpenId(data).then((openIdstr)=>{
							store.dispatch("SET_OPENID", openIdstr);
							goPay()
						})
					},
					fail :(req) => {
						console.log(req)
					}
				})
			// }else{
			// 	isClick1.value = false
			// 	isClick2.value = false
			// }
		}else{
			goPay()
		}
	}, 500)

	onLoad((options)=>{
		params.sourceBizId = options.id
		params.sourceBizType = options.type
		params.couponId = options.couponId?options.couponId.split(','):""
		if(options.payStatus){
			checked.value = 1
			params.channelCode = 'tonglian_wx_miniapp'
			goPay()
		}
	})
	onShow(()=>{
		let openId = uni.getStorageSync("openId");
		hasOpenId.value = openId? true : false
		// #ifdef MP-WEIXIN
		let options = wx.getEnterOptionsSync();
		if (options.scene == '1038' && options.referrerInfo.appId=='wxef277996acc166c3') {
			// 代表从收银台小程序返回
			let extraData = options.referrerInfo.extraData;
			if (!extraData) {
				// "当前通过物理按键返回，未接收到返参，建议自行查询交易结果";
			} else {
				if (extraData.code == 'success') {
					// "支付成功";
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					});
				} else if (extraData.code == 'cancel') {
					// "支付已取消";
					uni.showToast({
						title: '支付已取消',
						icon: 'none'
					});
				} else {
					// "支付失败：" + extraData.errmsg;
					uni.showToast({
						title: "支付失败：" + extraData.errmsg,
						icon: 'fail'
					});
				}
        options.scene == 1001
        options.referrerInfo = {}
        options.query = {}
				setTimeout(()=>{
					uni.navigateBack({
						delta: 2
					})
				},2000)
			}
		}
		// #endif
	})
</script>
<style>
	page{
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	.pay-box{
		display: flex;
		flex-direction: column;
		height: 100%;
		.pay-title{
			color: rgba(51, 51, 51, 1);
			margin: 0 30rpx;
			font-size: 30rpx;
			margin-top: 40rpx;
		}
		.item{
			display: flex;
			padding: 24rpx 0;
			.icon-1{
				width: 56rpx;
				height: 56rpx;
				margin: 0 25rpx 0 20rpx;
			}
			.icon-2{
				width: 50rpx;
				height: 50rpx;
			}
			.itm-title{
				flex: 1;
			}
		}
		.item-box{
			background: #fff;
			padding: 10rpx 20rpx;
			margin: 20rpx;
			border-radius: 6px;
		}
		.border{
			border-bottom: 2rpx solid rgba(242, 243, 245, 1);
		}
		.pay-btn{
			flex: 1;
			display: flex;
			.btn{
				width: 400rpx;
				height: 84rpx;
				border-radius: 54rpx;
				background: rgba(253, 150, 24, 1);
				color: #fff;
				text-align: center;
				line-height: 84rpx;
				font-size: 28rpx;
				margin: 600rpx auto 0 auto;
			}
			.isClick-style{
				background: rgba(219, 219, 219, 1);
			}
		}
	}
</style>

